package org.xian.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class MyProtobufEncoder extends MessageToByteEncoder<Packet> {

    private final int limit;

    public MyProtobufEncoder(int limit) {
        this.limit = limit;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Packet packet, ByteBuf byteBuf) throws Exception {
        if (packet.getPayload().length > limit) {
            throw new IllegalArgumentException();
        }
        // 请求或者响应的长度
        byteBuf.writeShort(packet.getPayload().length + 4);
        // 请求或者响应的指令码
        byteBuf.writeInt(packet.getCmd());
        // 请求或者的响应的内容
        byteBuf.writeBytes(packet.getPayload());
    }
}
